package com.dale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dale.common.dto.BlogDto;
import com.dale.entity.Blog;
import com.dale.entity.MetaBlog;
import com.dale.mapper.MetaBlogMapper;
import com.dale.mapper.MetaMapper;
import com.dale.service.MetaBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author  ：MarkerHub
 * @since 2020-05-25
 */
@Service
public class MetaBlogServiceImpl extends ServiceImpl<MetaBlogMapper, MetaBlog> implements MetaBlogService {

    @Autowired
    MetaBlogMapper metaBlogMapper;

    @Autowired
    MetaMapper metaMapper;

    @Override
    public IPage<BlogDto> queryBlogByMeta(Page<BlogDto> page, List metas) {
        return metaBlogMapper.queryBlogByMeta(page, metas);
    }

    @Override
    @Transactional //事务支持
    public void addMetaOnBlog(List<String> metas, Long blogId) {
        //1 先查出所有的mid
        List<Long> mids = metaMapper.getMidByNames(metas);

        Assert.isTrue(mids.size() != 0, "不能凭空分类哈");
        Assert.isTrue(mids != null, "不能凭空分类哈");


        //2 然后一一地插入 metaBlog关系表中
        for (Long mid : mids) {
            //如果该分类已存在 则停止插入 （又bid 和 mid共同确定）
            MetaBlog metaBlog = new MetaBlog();
            metaBlog.setBid(blogId);
            metaBlog.setMid(mid);

            MetaBlog metaBlog1 = metaBlogMapper.selectOne(new QueryWrapper<MetaBlog>()
                    .eq("bid", blogId)
                    .eq("mid", mid));

            if (metaBlog1 == null) {
                //表示该文章分类不存在 才插入
                metaBlogMapper.insert(metaBlog);
            }

        }

    }

    @Override
    public List<String> queryBlogMetas(Long bid) {
        return metaBlogMapper.queryBlogMetas(bid);
    }
}
